<?php
	
	class FieldController extends Controller
	{
		
		public $defaultAction = 'fields';
		
		public function actionFields()
		{
			$user = User::model()->findByPk(Yii::app()->user->getId());
			
			$fields = $user->settlement->fields;
		
			$flds = array();
			$resForHour = array();
			
			foreach($fields as $field)
			{
				$upd_price = $field->type->upd_price;
				foreach($upd_price as $key => $val){
					$upd_price[$key] = $upd_price[$key]*$field->lvl;
				}
				
				$flds[] = array('label' => 'Поле добывающее '.$field->type->resource->name.' ('.$field->lvl.') ', 'id'=>$field->id, 'upd_price' => $upd_price);
				
				if(!isset($resForHour[$field->type->resource->name]))
					$resForHour[$field->type->resource->name] = 0;
				$resForHour[$field->type->resource->name] += $field->type->count * $field->lvl;
			}
			
			$buildings = $user->settlement->buildings;
			$build = array();
			foreach($buildings as $b)
			{
				if($b->id_building == 3)
				{
					$build[] = $b;
				}
			}
				
			$nameResType = ResourcesType::model()->findByPk(4)->name;
			if(!isset($resForHour[$nameResType]))
				$resForHour[$nameResType] = 0;
			if(!empty($build))
			{
				foreach($build as $b)
				{
					$resForHour[$nameResType] += 20 * $b->lvl;
				}
			}
			
			$rfh = array();
			foreach($resForHour as $key => $res)
			{
				$rfh[] = array('id' => 1, 'Resource'=>$key, 'colh' => $res);
			}
			
			$gridDataProvider = new CArrayDataProvider($rfh);
			
			
			$unitType = UnitType::model()->findAll();
			$units = array();
			foreach($unitType as $ut)
			{
				$unit = Units::model()->findAll("id_settlement = " . $user->current_settlement . " and id_unit = " . $ut->id);
				$count = count($unit);

				if($count == 0)
					continue;
					
				$units[] = array('id' => 1, 'Name'=>$ut->name, 'Count' => $count);
			}
			$gridDataProviderUnit = new CArrayDataProvider($units);
			
			$this->render('fields', array('fields' => $flds, 'stats' => $gridDataProvider, 'units' => $gridDataProviderUnit));
		}
		
		public function actionLevelUp()
		{
			$field = Fields::model()->findByPk($_GET['id']);
			$upd_price = $field->type->getUpdPrice();
			
			if(!Controller::levelUp($field, $upd_price))
			{
				Yii::app()->user->setFlash('error', 'Недостаточно ресурсов');
				$this->redirect($this->createUrl('field/fields'));
			}
			
			$this->redirect($this->createUrl('field/fields'));
			
		}
		
	}